package cn.icanci.template.handler;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;

/**
 * @Author: icanci
 * @ProjectName: kangaroo-orm
 * @PackageName: cn.icanci.template.handler
 * @Date: Created in 2020/8/31 15:50
 * @ClassAction: 处理单个对象的结果集
 */
public class BeanHandler<T> implements IResultSetHandler<T> {

    // 把结果集中的一行数据封装成一个对象
    private Class<T> classType;

    public BeanHandler(Class<T> classType) {
        this.classType = classType;
    }

    @Override
    public T handler(ResultSet rs) throws Exception {
        if (null == rs) {
            return classType.newInstance();
        }
        T obj = classType.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(classType, Object.class);
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        while (rs.next()) {
            for (PropertyDescriptor pd : pds) {
                String columnName = pd.getName();
                Object value = rs.getObject(columnName);
                pd.getWriteMethod().invoke(obj, value);
            }
        }
        return obj;
    }
}
